package com.flashcash.solu.view;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.flashcash.kotlin.activity.LoaningActivity;
import com.flashcash.kotlin.data.ProductBean;
import com.flashcash.kotlin.fragment.LoanNormalFragment1;
import com.flashcash.kotlin.fragment.ProductFragment;
import com.flashcash.kotlin.trace.TraceManager;
import com.flashcash.kotlin.utils.FirebaseAnalyticsConstants;
import com.flashcash.kotlin.utils.FirebaseAnalyticsUtils;
import com.flashcash.solu.BuildConfig;
import com.flashcash.solu.R;
import com.flashcash.solu.app.base.BaseActivity;
import com.flashcash.solu.app.base.BaseFragment;
import com.flashcash.solu.bean.LatestLoanAppBean;
import com.flashcash.solu.bean.ProgressBean;
import com.flashcash.solu.bean.TotalAmount;
import com.flashcash.solu.common.EventCollection;
import com.flashcash.solu.common.FieldParams;
import com.flashcash.solu.common.TokenManager;
import com.flashcash.solu.harvester.collectin.Collector;
import com.flashcash.solu.harvester.collectin.PermissionUtil;
import com.flashcash.solu.harvester.uploadout.UploadUtils;
import com.flashcash.solu.utils.ACache;
import com.flashcash.solu.utils.CommonUtils;
import com.flashcash.solu.view.certification.CertifyActivity;
import com.flashcash.solu.view.certification.FacebookAccountActivity;
import com.flashcash.solu.view.fragment.MeFragment;
import com.flashcash.solu.view.fragment.presenter.LoanNormalFraPreImp;
import com.flashcash.solu.view.loan.LoanNormalFragment1Activity;
import com.flashcash.solu.view.loan.MyLoanFragment;
import com.flashcash.solu.view.presenter.MainActPreImp;
import com.flashcash.solu.view.presenter.MainActPresenter;
import com.flashcash.solu.widget.selfdefdialog.DialogManager;
import com.flashcash.solu.widget.selfdefdialog.XLeoProgressDialog;
import com.flashcash.solu.widget.xleotoast.XLeoToast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.InstanceIdResult;
import com.google.firebase.messaging.FirebaseMessaging;
import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.kredit.kotlin.firebase.FirebaseUtil;
import com.tbruyelle.rxpermissions.Permission;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.x.leo.apphelper.documented.DocumentMessage;
import com.x.leo.apphelper.log.XLog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.tongdun.android.shell.FMAgent;
import cn.tongdun.android.shell.exception.FMException;
import rx.Observable;
import rx.Subscriber;
import rx.subjects.PublishSubject;


public class MainActivity extends BaseActivity<MainActPresenter> implements MainActView {
    private static final String TAG = "MainActivity";

    private static final int TAB_LOAN = 0x0010;
    private static final int TAB_CERT = 0x0020;
    private static final int TAB_ME = 0x0030;

    @BindView(R.id.id_textview_tab_home)
    TextView textViewLoan;

    @BindView(R.id.id_textview_tab_my_loan)
    TextView textViewCertification;

    @BindView(R.id.id_textview_tab_me)
    TextView textViewMe;

    // current tab
    private int currentSelectedTab;
    // current fragment
    private BaseFragment currentFragment;

    // loan tab
    ProductFragment productFragment;
    //    LoanNormalFragment1 loanNormalFragment1;
//    LoanInProcessFragment loanInProcessFragment;
//    LoanRepaymentFragment loanRepaymentFragment;
//    LoanRepaymentExpiryFragment loanRepaymentExpiryFragment;

    // cert tab
//    CertifyFragment certifyFragment;
    MyLoanFragment myLoanFragment;

    // me tab
    MeFragment meFragment;

    /**
     * after called qualification api successfully will post an event
     * to{@link #setLoaningFragment(EventCollection.GotoLoanApplicationTabEvent)}, then update this
     * field{@link LoanNormalFraPreImp#qualificateLoan()}
     */
    public static TotalAmount selectedTotalAmount;
    /**
     * after called qualification api successfully will update this
     * field{@link LoanNormalFraPreImp#qualificateLoan()}
     */
    public static Boolean isSubmitVisible = false;

    // broadcast receiver for app update
    private BroadcastReceiver broadcastReceiver;

    private long mUploadFirebaseTokenTs = 0;

    private boolean isPermissionChecked;

    private ACache aCache;
    private static final String KEY_CACHE_FINISH = "cache_finish";

    private static final String KEY_SHOW_CREDIT_TIPS = "show_credit_toast";
    private static final String KEY_FROM_INTRODUCE = "from_introduce";
    private static final String KEY_ADD_USER = "add_user";
    private static final String KEY_QUALIFICATION_ERR_MSG = "QUALIFICATION_ERR_MSG";

    private boolean showLaterDialog;//是否显示几天后才可以重新提交贷款的弹出框
    private boolean requestQualification;//是否请过过

    /**
     * 跳转到MainActivity并弹出认证提示信息
     *
     * @param context
     * @param addUser
     */
    public static void startMainActivityAndShowCreditTips(Context context, boolean addUser) {
        context.startActivity(new Intent(context, MainActivity.class).putExtra(KEY_SHOW_CREDIT_TIPS, true).putExtra(KEY_ADD_USER, addUser));
    }

    public static void startMainActivityFromIntroduce(Context context) {
        Intent intent = new Intent(context, MainActivity.class);
        intent.putExtra(KEY_FROM_INTRODUCE, true);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    protected MainActPresenter initPresenterImpl() {
        return new MainActPreImp();
    }

    @Override
    protected void init() {
        Collector.init(this);
        UploadUtils.init(this);

        rx.Observable.just(1)
                .delay(10, TimeUnit.SECONDS)

                .subscribe(t -> {
                    if (!TextUtils.isEmpty(UploadUtils.getLoanId(MainActivity.this))) {
                        UploadUtils.startUploadingFromLocal();
                    }
                });

        Collector.init(this);
        UploadUtils.init(this);

        RxBus.get().register(this);
        bindBroadcastReciver();

        // appsflyer

        setSelectLoan();


        /*Observable
                .just(1)
//                .delay(1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .map(t -> imeiCollectTipDialogShowed())
                .compose(bindToLifecycle())
                .observeOn(AndroidSchedulers.mainThread())
                .flatMap((Func1<Boolean, Observable<Boolean>>) showed -> {
                    if (showed == null || !showed) {
                        return imeiTipDialog();
                    } else {
                        return Observable.just(true);
                    }
                })
                .doOnNext(okSelected -> {
                    if (!okSelected) {
                        finish();
                    }
                })
                .subscribe(t -> {
                    requestPermissions(0);
                });*/
        requestPermissions(0);//直接请求权限


        // bind account for ali push
//        bindAccountWhenChannelOKAndLoginOK();
        mPresenter.requestMarket();
//        FacebookAccountActivity.startFacebookAccountActivity(this,true);
//        showLoaningActivity();

        aCache = ACache.get(this);
        String finished = aCache.getAsString(KEY_CACHE_FINISH);
        if (!"1".equals(finished)) {//没有完成四步认证，就请求信息
            mPresenter.updateCertifyState();
        }
//        startActivity(new Intent(this, SubmittedLoanActivity.class));
        if (getIntent() != null && getIntent().getBooleanExtra(KEY_SHOW_CREDIT_TIPS, false)) {
            FirebaseAnalyticsUtils.INSTANCE.logEvent(FirebaseAnalyticsConstants.Event.SHOW_CREDIT_TIPS, null);
            XLeoToast.showMessage(getString(R.string.tips_credit));
            if (getIntent().getBooleanExtra(KEY_ADD_USER, false)) {
                addUserInfo();
            }
        }
        if (getIntent() != null && getIntent().getBooleanExtra(KEY_FROM_INTRODUCE, false)) {
            addUserInfo();
            XLeoToast.showMessage("Login Success");
        }
//        mPresenter.isQualification(null);
    }

    private OnCompleteListener<InstanceIdResult> mFirebaseListener = new OnCompleteListener<InstanceIdResult>() {
        @Override
        public void onComplete(@NonNull Task<InstanceIdResult> task) {
            if (!task.isSuccessful()) {
                Log.w(TAG, "getInstanceId failed", task.getException());
                return;
            }

            // Get new Instance ID token
            String token = task.getResult().getToken();

            // Log and toast
            Log.i(TAG, "FCM id " + task.getResult().getId() + " token " + token);
            FirebaseUtil.saveFirebaseToken(MainActivity.this, token);
        }
    };

    private OnCompleteListener<Void> mFirebaseTopicListener = new OnCompleteListener<Void>() {
        @Override
        public void onComplete(@NonNull Task<Void> task) {
            Log.i(TAG, "subscribeToTopic onComplete");
        }
    };

    @Override
    protected void onResume() {
        super.onResume();

        Log.i("MainOnResume", "hello world");


        if (FirebaseInstanceId.getInstance() != null) {
            FirebaseInstanceId.getInstance().getInstanceId().addOnCompleteListener(mFirebaseListener);
        }
        if (FirebaseMessaging.getInstance() != null) {
            FirebaseMessaging.getInstance().subscribeToTopic(getString(R.string.app_name).replaceAll(" ", "")).addOnCompleteListener(mFirebaseTopicListener);
            FirebaseMessaging.getInstance().subscribeToTopic((getString(R.string.app_name) + BuildConfig.VERSION_NAME + BuildConfig.VERSION_CODE).replaceAll(" ", "")).addOnCompleteListener(mFirebaseTopicListener);
        }
        if (!TextUtils.isEmpty(FirebaseUtil.getFirebaseToken(this)) && !TextUtils.isEmpty(TokenManager.getInstance().getToken())) {
            if (System.currentTimeMillis() - mUploadFirebaseTokenTs > 60 * 1000) {
                FirebaseUtil.resume();
                FirebaseUtil.uploadFirebaseTokenWithRetry(FirebaseUtil.getFirebaseToken(this));
            }
            mUploadFirebaseTokenTs = System.currentTimeMillis();
        }
    }

    private void requestPermissions(int permissionIndex) {
        if (dialog != null && dialog.isShowing()) {
            return;
        }

        if (permissionIndex >= PermissionUtil.neededPermissions.length) {
            return;
        }

        String perm = PermissionUtil.neededPermissions[permissionIndex];

        if (!Collector.permissionGranted(perm, this)) {
            new RxPermissions(this)
                    .requestEach(perm)
                    .subscribe(new Subscriber<Permission>() {
                        @Override
                        public void onCompleted() {
                        }

                        @Override
                        public void onError(Throwable e) {
                        }

                        @Override
                        public void onNext(Permission permission) {

//                            if (!permission.granted) {
//                                    showDialog(permission, permissionIndex);
//                            } else {
                            requestPermissions(permissionIndex + 1);
                            //}
                        }
                    });

        } else {
            requestPermissions(permissionIndex + 1);
        }
    }


    AlertDialog dialog;

    private void showDialog(Permission permission, int permissionIndex) {
        if (dialog != null) {
            dialog.dismiss();
        }

        dialog = new AlertDialog.Builder(MainActivity.this)
                .setTitle(android.R.string.dialog_alert_title)
                .setCancelable(false)
                .setPositiveButton(android.R.string.ok, (d, which) -> {

                    d.dismiss();
                    if (permission.shouldShowRequestPermissionRationale) {
                        requestPermissions(permissionIndex);

                    } else {
                        TraceManager.INSTANCE.toSettingPermissionActivity(MainActivity.this, PermissionUtil.neededPermissions[permissionIndex]);
                    }
                })
                .create();

        dialog.setMessage(MainActivity.this.getString(R.string.need_permission_to_loan)
                + "\n\n" + PermissionUtil.getPermisinssionDesc(MainActivity.this, permissionIndex));


        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    protected void onDestroy() {
        RxBus.get().unregister(this);
        unregisterReceiver(broadcastReceiver);

        XLog.INSTANCE.i("destroy", 10);

        if (dialog != null) {
            dialog.dismiss();
        }
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (TokenManager.getInstance().hasLogin() && currentFragment != null && productFragment
                != null && currentFragment instanceof
                LoanNormalFragment1) {
            showLoan();
            return;
        }
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addCategory(Intent.CATEGORY_HOME);
        startActivity(intent);
    }

    private Observable<Boolean> imeiTipDialog() {
        return Observable.create(subscriber -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Attention").setMessage(R.string
                    .msg_imei_tips).setPositiveButton("Confirm", (dialog1, which) -> {
                saveImeiCollectTipDialogShowed();
                subscriber.onNext(true);
            }).setNegativeButton("Cancel", (dialog12, which) -> {
                subscriber.onNext(false);
            });
            AlertDialog dialog = builder.create();
            dialog.setCanceledOnTouchOutside(false);
            dialog.setOnKeyListener((dialog13, keyCode, event) -> true);
            dialog.show();
        });
    }

    private Boolean imeiCollectTipDialogShowed() {
        DocumentMessage doc = DocumentMessage.Companion.getDoc();
        return doc.getBoolean(getImeiTipSettingKey(), false);
    }

    private void saveImeiCollectTipDialogShowed() {
        DocumentMessage doc = DocumentMessage.Companion.getDoc();
        doc.putBoolean(getImeiTipSettingKey(), true);
    }

    private String getImeiTipSettingKey() {
        return FieldParams.IMEI_COLLECT_TIP_SHOWED_KEY + "_" + BuildConfig.VERSION_CODE;
    }

    @OnClick(R.id.id_textview_tab_home)
    public void setSelectLoan() {
        if (currentSelectedTab == TAB_LOAN) {
            return;
        }

        showLoan();
    }

    private void showLoan() {
        clearTabSelection();
        currentSelectedTab = TAB_LOAN;
        textViewLoan.setSelected(true);

        if (!TokenManager.getInstance().hasLogin()) {
            mPresenter.requestProductsDefault();
        } else {
            mPresenter.requestLatestAndProducts();
        }
    }

    @OnClick(R.id.id_textview_tab_my_loan)
    public void setSelectCertify() {
        if (currentSelectedTab == TAB_CERT) {
            return;
        }

        isSubmitVisible = false;
//        showCertifyFragment();
        showMyLoanFragment();
    }

    /*private void showCertifyFragment() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction();
        clearTabSelection();
        if (currentFragment != null) {
            fragmentTransaction.hide(currentFragment);
        }
        if (certifyFragment == null) {
            certifyFragment = new CertifyFragment();
            fragmentTransaction.add(R.id.id_fragment_loan, certifyFragment, certifyFragment
                    .getTag());
        } else {
            fragmentTransaction.show(certifyFragment);
        }
        currentFragment = certifyFragment;
        currentSelectedTab = TAB_CERT;
        textViewCertification.setSelected(true);
        fragmentTransaction.commitAllowingStateLoss();
    }*/

    private void showMyLoanFragment() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction();
        clearTabSelection();
        if (currentFragment != null) {
            fragmentTransaction.hide(currentFragment);
        }
        if (myLoanFragment == null) {
            myLoanFragment = new MyLoanFragment();
            fragmentTransaction.add(R.id.id_fragment_loan, myLoanFragment, myLoanFragment
                    .getTag());
        } else {
            fragmentTransaction.show(myLoanFragment);
        }
        currentFragment = myLoanFragment;
        currentSelectedTab = TAB_CERT;
        textViewCertification.setSelected(true);
        fragmentTransaction.commitAllowingStateLoss();
    }

    @OnClick(R.id.id_textview_tab_me)
    public void setSelectMe() {
        if (currentSelectedTab == TAB_ME) {
            return;
        }

        showMeFragment();
    }

    private void showMeFragment() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction();
        clearTabSelection();
        if (currentFragment != null) {
            fragmentTransaction.hide(currentFragment);
        }
        if (meFragment == null) {
            meFragment = new MeFragment();
            fragmentTransaction.add(R.id.id_fragment_loan, meFragment, meFragment.getTag());
        } else {
            fragmentTransaction.show(meFragment);
        }
        currentFragment = meFragment;
        currentSelectedTab = TAB_ME;
        textViewMe.setSelected(true);
        fragmentTransaction.commitAllowingStateLoss();
    }

    private AlertDialog productsDefaultErrorDialog;
    private AlertDialog latestAndProductsErrorDialog;

    @Override
    public void onResponseProductsDefaultError(String errorMsg) {
        if (productsDefaultErrorDialog == null) {
            productsDefaultErrorDialog = new AlertDialog.Builder(this)
                    .setCancelable(false)
                    .setTitle(R.string.tips_title)
                    .setMessage(errorMsg)
                    .setPositiveButton(R.string.retry, (dialog, which) -> {
                        dialog.dismiss();
                        mPresenter.requestProductsDefault();
                    }).create();
        }
        if (!productsDefaultErrorDialog.isShowing()) {
            productsDefaultErrorDialog.show();
        }
    }

    @Override
    public void onResponseLatestAndProductsError(String errorMsg) {
        if (latestAndProductsErrorDialog == null) {
            latestAndProductsErrorDialog = new AlertDialog.Builder(this)
                    .setCancelable(false)
                    .setTitle(R.string.tips_title)
                    .setMessage(errorMsg)
                    .setPositiveButton(R.string.retry, (dialog, which) -> {
                        dialog.dismiss();
                        mPresenter.requestLatestAndProducts();
                    }).create();
        }
        if (!latestAndProductsErrorDialog.isShowing()) {
            latestAndProductsErrorDialog.show();
        }
    }

    @Override
    public void showLoanRepayExpiry() {
        /*if (currentSelectedTab == TAB_LOAN) {
            showLoanRepayExpiryFragment();
        }*/
    }

    /*private void showLoanRepayExpiryFragment() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction();
        if (currentFragment != null) {
            fragmentTransaction.hide(currentFragment);
        }
        if (loanRepaymentExpiryFragment == null) {
            loanRepaymentExpiryFragment = new LoanRepaymentExpiryFragment();
            fragmentTransaction.add(R.id.id_fragment_loan, loanRepaymentExpiryFragment,
                    loanRepaymentExpiryFragment.getTag());
        } else {
            fragmentTransaction.show(loanRepaymentExpiryFragment);
        }
        currentFragment = loanRepaymentExpiryFragment;
        fragmentTransaction.commitAllowingStateLoss();
    }*/

    @Override
    public void showLoanRepay() {
        /*if (currentSelectedTab == TAB_LOAN) {
            showLoanRepaymentFragment();
        }*/
    }

    /*private void showLoanRepaymentFragment() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction();
        if (currentFragment != null) {
            fragmentTransaction.hide(currentFragment);
        }
        if (loanRepaymentFragment == null) {
            loanRepaymentFragment = new LoanRepaymentFragment();
            fragmentTransaction.add(R.id.id_fragment_loan, loanRepaymentFragment,
                    loanRepaymentFragment.getTag());
        } else {
            fragmentTransaction.show(loanRepaymentFragment);
        }
        currentFragment = loanRepaymentFragment;
        fragmentTransaction.commitAllowingStateLoss();
    }*/

    @Override
    public void showLoanInProcess() {
        /*if (currentSelectedTab == TAB_LOAN) {
            showLoanInProcessFragment();
        }*/
    }

    /*private void showLoanInProcessFragment() {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction();
        if (currentFragment != null) {
            fragmentTransaction.hide(currentFragment);
        }
        if (loanInProcessFragment == null) {
            loanInProcessFragment = new LoanInProcessFragment();
            fragmentTransaction.add(R.id.id_fragment_loan, loanInProcessFragment,
                    loanInProcessFragment.getTag());
        } else {
            fragmentTransaction.show(loanInProcessFragment);
        }
        currentFragment = loanInProcessFragment;
        fragmentTransaction.commitAllowingStateLoss();
    }*/

    @Override
    public void showLoanProducts(ArrayList<ProductBean> productBeanList) {
        if (currentSelectedTab == TAB_LOAN) {
            showProductFragment(productBeanList);
        }
    }

    private void showProductFragment(ArrayList<ProductBean> productBeanList) {
        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction();
        if (currentFragment != null) {
            fragmentTransaction.hide(currentFragment);
        }
        if (productFragment == null) {
            productFragment = ProductFragment.Companion.newInstance(productBeanList);
            fragmentTransaction.add(R.id.id_fragment_loan, productFragment, productFragment
                    .getTag());
        } else {
            productFragment.setProductBeanList(productBeanList);
            fragmentTransaction.show(productFragment);
        }
        currentFragment = productFragment;
        fragmentTransaction.commitAllowingStateLoss();
    }

    @Override
    public void showLoanNormal(ProductBean productBean) {
        if (currentSelectedTab == TAB_LOAN) {
            if (!requestQualification) {//还没请求过合格接口
                mPresenter.isQualification(productBean);
            } else {//请求过了接口
                if (showLaterDialog) {//不合格，显示窗口
                    View view = View.inflate(context, R.layout.dialog_loan_click_reject, null);
                    ImageView buttonTv = view.findViewById(R.id.btn_result_failed);
                    Dialog dialog = DialogManager.newDialog(context, view, false);
                    buttonTv.setOnClickListener(v -> dialog.dismiss());
                    TextView tv = view.findViewById(R.id.message);
                    tv.setText(aCache.getAsString(KEY_QUALIFICATION_ERR_MSG));
                    if (aCache.getAsString(KEY_QUALIFICATION_ERR_MSG).contains("sorry,already had active loan")) {//不显示
                    } else {
                        CommonUtils.initMarketImage(view, context);
                    }
                    dialog.show();
                } else {
                    showLoanNormalFragment(productBean);
                }
            }
        }
    }

    private void showLoanNormalFragment(ProductBean productBean) {
        Log.e("productBean", productBean.toString());
        LoanNormalFragment1Activity.startActivity(this, productBean);
        /*FragmentTransaction fragmentTransaction = getSupportFragmentManager()
                .beginTransaction();
        if (currentFragment != null) {
            fragmentTransaction.hide(currentFragment);
        }
        if (loanNormalFragment1 == null) {
            loanNormalFragment1 = LoanNormalFragment1.Companion.newInstance(productBean);
            fragmentTransaction.add(R.id.id_fragment_loan, loanNormalFragment1,
                    loanNormalFragment1.getTag());
        } else {
            loanNormalFragment1.setProductBean(productBean);
            fragmentTransaction.show(loanNormalFragment1);
        }
        currentFragment = loanNormalFragment1;
        fragmentTransaction.commitAllowingStateLoss();*/
    }

    private void showLoaningActivity() {
        startActivity(new Intent(this, LoaningActivity.class));
    }

    /**
     * 申请贷款通过
     */
    @Override
    public void showLoanSuccess() {
        View view = View.inflate(this, R.layout.dialog_loan_success, null);
        Dialog dialog = new XLeoProgressDialog(this);
        view.findViewById(R.id.btn_dialog_current_oko).setOnClickListener(v -> dialog.dismiss());
        dialog.setContentView(view);
        dialog.show();
    }

    @Override
    public void showLoanReject() {
        View view = View.inflate(this, R.layout.dialog_loan_failed, null);
        final ImageView buttonTv = view.findViewById(R.id.btn_result_failed);
        Dialog dialog = DialogManager.newDialog(this, view, false);
        buttonTv.setOnClickListener(v -> dialog.dismiss());
        //获取缓存好的市场app
        CommonUtils.initMarketImage(view, context);
        dialog.show();
    }

    @Override
    public void showLoanClosed(LatestLoanAppBean latestLoanAppBean) {
        View view = View.inflate(this, R.layout.dialog_loan_closed, null);
        Dialog dialog = new XLeoProgressDialog(this);
        TextView textView = view.findViewById(R.id.id_textview_closed_dialog_content);

        if (latestLoanAppBean != null && latestLoanAppBean.getComments() != null) {
            String[] closedReasons = latestLoanAppBean.getComments().split(",");
            StringBuilder closedReasonsStr = new StringBuilder();
            for (int j = 1; j <= closedReasons.length; j++) {
                closedReasonsStr.append(j).append(". ").append(closedReasons[j - 1]).append
                        ("\n");
            }
            textView.setText(closedReasonsStr.toString());
        } else {
            textView.setText(null);
        }

        view.findViewById(R.id.id_button_goto_modify).setOnClickListener(v -> dialog.dismiss());
        dialog.setContentView(view);
//        CommonUtils.initMarketImage(view, context);
        dialog.show();
    }

    @Override
    public void onAddUserInfoSuccess() {
//        XLog.INSTANCE.d("调用成功", 10);
        /*new AlertDialog.Builder(this)
                .setCancelable(false)
                .setTitle(R.string.tips_title)
                .setMessage("调用addUserInfo接口成功")
                .setPositiveButton("确定", (dialog, which) -> {
                    dialog.dismiss();
                }).create().show();*/
    }

    /**
     * 同步认证信息成功
     *
     * @param progressBean
     */
    @Override
    public void updateCertifyStateSuccess(ProgressBean progressBean) {
//        XLeoToast.showMessage(""+progressBean.isCompleted());
        aCache.put(KEY_CACHE_FINISH, progressBean.isCompleted() ? "1" : "0");
    }

    /**
     * 是否合格的回调
     *
     * @param errorMsg    为空串则为合格，非空为不合格
     * @param productBean 不合格时，是否显示弹出框
     */
    @Override
    public void qualification(String errorMsg, ProductBean productBean) {
        if (!TextUtils.isEmpty(errorMsg)) {//不合格
            if (productBean != null) {//弹框提示
                View view = View.inflate(context, R.layout.dialog_loan_click_reject, null);
                ImageView buttonTv = view.findViewById(R.id.btn_result_failed);
                Dialog dialog = DialogManager.newDialog(context, view, false);
                buttonTv.setOnClickListener(v -> dialog.dismiss());
                TextView tv = view.findViewById(R.id.message);
                tv.setText(errorMsg);
                //获取缓存好的市场app
                if (errorMsg.contains("sorry,already had active loan")) {//不显示

                } else {
                    CommonUtils.initMarketImage(view, context);
                }
                dialog.show();
            }
            showLaterDialog = true;
            aCache.put(KEY_QUALIFICATION_ERR_MSG, errorMsg);
        } else {//合格
            if (productBean != null) {//跳转到详情页面
                showLoanNormalFragment(productBean);
            }
            showLaterDialog = false;
        }
        requestQualification = true;
    }

    /**
     * 完成四步认证
     *
     * @param event
     */
    @Subscribe
    public void onFinishCertify(EventCollection.FirstFinishCertifyEvent event) {
        if (aCache != null) {
            aCache.put(KEY_CACHE_FINISH, "1");
        }
    }

    public void addUserInfo() {
        try {
            Map<String, Object> options = new HashMap<>();
            options.put(FMAgent.OPTION_DOMAIN, "https://idfptest.tongdun.net");
            options.put(FMAgent.OPTION_BLACKBOX_MAXSIZE, 5 * 1024);
            FMAgent.initWithCallback(context, FMAgent.ENV_PRODUCTION, options, blackbox -> {
                // 注意这里不是主线程 请不要在这个函数里进行ui操作，否则可能会出现崩溃
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mPresenter.addUserInfo(TokenManager.getInstance().getMobile(), blackbox);
                    }
                });
            });
        } catch (FMException e) {
            e.printStackTrace();
        }
    }

    private void clearTabSelection() {
        textViewLoan.setSelected(false);
        textViewCertification.setSelected(false);
        textViewMe.setSelected(false);
    }

    private void bindBroadcastReciver() {
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (FieldParams.BroadcastAction.NEW_MESSAGE.equals(action)) {
                    showMessageUpdate();
                }
            }
        };
        IntentFilter filter = new IntentFilter(FieldParams.BroadcastAction.BROADCASTACTION_UPDATE);
        filter.addAction(FieldParams.BroadcastAction.NEW_MESSAGE);
        registerReceiver(broadcastReceiver, filter);
        XLog.INSTANCE.i("register receiver", 12);
    }

    private void showMessageUpdate() {
        if (currentFragment != null) {
            currentFragment.informMessage();
        }
    }

    /**
     * event posted from: called qualificateLoan api
     *
     * @param event
     */
    @Subscribe
    public void setLoaningFragment(EventCollection.GotoLoanApplicationTabEvent event) {
        if (isActive()) {
            selectedTotalAmount = event.getTotalAmount();
            XLog.INSTANCE.d("Set Loaning Fragment", 10);

            /*setSelectedTab(TAB_CERT);*/
            //
//            showCertifyFragment();

            String finished = aCache.getAsString(KEY_CACHE_FINISH);
            if ("1".equals(finished)) {//完成了四步认证，则直接跳转到facebook页面
                FacebookAccountActivity.startFacebookAccountActivity(this, true);
            } else {
                CertifyActivity.startCertifyActivityAndGotoLoaning(context);
            }
        }
    }

    /**
     * event posted from: called LoanNormalFragment1Activity
     *
     * @param event
     */
    @Subscribe
    public void updateProducts(EventCollection.LoanEvent event) {
        if (TokenManager.getInstance().hasLogin() && currentFragment != null && productFragment != null) {
            showLoan();
        }
    }

    /**
     * event posted from: okHttp interceptor
     *
     * @param event
     */
    @Subscribe
    public void onTokenExpried(TokenManager.TokenExpiredEvent event) {
        toLogin();
    }

    public PublishSubject<Boolean> loginOk = PublishSubject.create();

    /**
     * event posted from: called login api successful
     *
     * @param event
     */
    @Subscribe
    public void onSelectLoanStatus(EventCollection.AccoutUpdateEvent event) {
        XLog.INSTANCE.d("LoginActivity.ReSetLoanStatusEvent", 10);

//        bindAccountForAliPush();

        showLoan();

        loginOk.onNext(true);
    }

    /**
     * event posted from: called uploadFaces api successful
     *
     * @param event
     */
    @Subscribe
    public void onSelectLoaningFragment(EventCollection.GotoLoaning event) {
        if (event.getTotalAmount() != null) {
            selectedTotalAmount = event.getTotalAmount();
//            Toast.makeText(this, selectedTotalAmount.getProductId()+"", Toast.LENGTH_SHORT).show();
        }
        XLog.INSTANCE.i("onSelectLoaningFragment", 10);
        showLoaningActivity();
        isSubmitVisible = false;
    }


    /**
     * event posted from: called uploadBankInfo api successful
     *
     * @param event rx bus event
     */
    @Subscribe
    public void onLoanSuccess(EventCollection.LoanSuccess event) {
        mPresenter.uploadXTrace();
        showLoan();
        if (myLoanFragment != null) {
            myLoanFragment.requestData();
        }
    }

    /**
     * event posted from: called SubmittedLoanActivity
     *
     * @param event rx bus event
     */
    @Subscribe
    public void onGotoMyLoan(EventCollection.GotoMyLoan event) {
        showMyLoanFragment();
    }


    /**
     * event posted from: called logout api successful/failed
     */
    @Subscribe
    public void onLogOut(EventCollection.LogoutEvent event) {
//        showLoan();
        aCache.put(FieldParams.ACacheKeys.ACACHE_FINISH_IDENTIFY, "0");
        startActivity(new Intent(this, IntroduceActivity.class));
        finish();
    }

    @Subscribe
    public void onVideoGiveUp(EventCollection.VideoGiveUp event) {
        showLoan();
    }

    /**
     * event posted from: canceled login
     */
    @Subscribe
    public void onGiveUpLogin(EventCollection.GiveUpLogin event) {
        showLoan();
    }

    /**
     * event posted from: called cancelLoan api successful/failed
     *
     * @param event
     */
    @Subscribe
    public void onCancelLoan(EventCollection.CancelLoan event) {
        showLoan();
    }

    /**
     * event posted from: okHttp interceptor
     *
     * @param event
     */
    @Subscribe
    public void updateSoftWare(EventCollection.NeedUpdateEvent event) {
        mPresenter.updateApk(event);
    }

    /**
     * event posted from: okHttp interceptor
     *
     * @param event
     */
    @Subscribe
    public void paramsMissing(EventCollection.ParamsMissingEvent event) {
        XLog.INSTANCE.i("missing params", 10);
    }

    /**
     * event posted from: product chose
     */
    @Subscribe
    public void onProductChose(EventCollection.ProductChoseEvent event) {
//        showLoanNormal(event.getProductBean());
        mPresenter.isQualification(event.getProductBean());
    }

    /**
     * Only when init ali push channel successfully and login successfully, then bind ali push account
     */
//    private void bindAccountWhenChannelOKAndLoginOK() {
//        Observable.combineLatest(App.instance.channelOK.asObservable(), loginOk.asObservable(),
//                (Func2<Boolean, Boolean, Object>) (aBoolean, aBoolean2) -> aBoolean && aBoolean2)
//                .filter(t -> true)
//                .subscribe(t -> bindAccountForAliPush());
//    }

    /**
     * bind account for ali push
     */
//    private void bindAccountForAliPush() {
//        //bind account for ali push
//        if (!TextUtils.isEmpty(TokenManager.getInstance().getMobile())) {
//            PushServiceFactory.getCloudPushService().bindAccount(TokenManager.getInstance()
//                    .getMobile(), new CommonCallback() {
//
//                @Override
//                public void onSuccess(String s) {
//                    Log.i(TAG, "onSuccess -> " + s);
//                }
//
//                @Override
//                public void onFailed(String s, String s1) {
//                    Log.d(TAG, "onFailed -> s = " + s + ", s1 = " + s1);
//                }
//            });
//        }
//    }
}
